import axios from "axios"
import { Commit } from "vuex"
import store from "@/store/store"
// 发送请求前 设置loading状态为true
axios.interceptors.request.use(config => {
  store.commit('setLoading', true)
  store.commit('setError', { status: false, message: '' })
  return config
})
// 收到请求前 设置loading状态为false
axios.interceptors.response.use(config => {
  store.commit('setLoading', false)
  return config
}, e => {
  console.log(e.response);
  const { error } = e.response.data
  store.commit('setError', { status: true, message: error })
  store.commit('setLoading', false)
  return Promise.reject(error)
})

export const getAndCommit = async (url: string, mutationsName: string, commit: Commit) => {
  const { data } = await axios.get(url)
  commit(mutationsName, data)
  // 这里也要返回带有data的promise，否则在编辑文章的时候，无法通过then得到数据
  return data
}

export const postAndCommit = async (url: string, mutationsName: string, commit: Commit, payload: any) => {
  const { data } = await axios.post(url, payload)
  commit(mutationsName, data)
  // 返回带有data的promise
  return data
}